package com.azhoucode.config;

import com.azhoucode.common.RedisProperties;
import com.azhoucode.util.RedisCacheUtils;
import freemarker.template.utility.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfiguration {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisProperties redisProperties;

    /**
     * jedisPool bean注册
     *
     * @return  {@link JedisPool}
     */
    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig config = getRedisConfig();
        JedisPool jedisPool = new JedisPool(config, redisProperties.getHost(),
                redisProperties.getPort(), redisProperties.getTimeout(),
                StringUtil.emptyToNull(redisProperties.getPassword()));
        RedisCacheUtils.setPool(jedisPool);
        logger.info("jedisPool初始化，节点：" + redisProperties.getHost() + ":" + redisProperties.getPort());
        return jedisPool;

    }

    @Bean
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisProperties.getMaxActive());
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMaxWaitMillis(redisProperties.getMaxWait());
        config.setMinIdle(redisProperties.getMinIdle());
        return config;
    }

}
